<template>
  <div :class="[`w-full px-4 pb-6 pt-2 bg-white`, needShadow ? 'shadow' : '']">
    <!-- 顶部进度条 -->
    <div class="w-full flex items-center my-4">
      <van-slider
        v-model="currentTime"
        :min="0"
        :max="duration"
        :step="1"
        :button-size="12"
        bar-height="4px"
        active-color="#436BFF"
        inactive-color="#F0F0F0"
        @drag-start="isSliding = true"
        @drag-end="isSliding = false"
        @change="onSliderChange"
        class="flex-1"
      >
        <template #button>
          <div class="w-3 h-3 bg-primary rounded-full"></div>
        </template>
      </van-slider>
    </div>
    <!-- 播放器主控件 -->
    <div class="flex items-center justify-between">
      <!-- 进度条和时间显示 -->
      <div />

      <div class="flex items-center gap-3 absolute">
        <div class="text-xs text-gray-400 min-w-[45px] tabular-nums">
          {{ formatTime(currentTime) }}/{{ formatTime(duration) }}
        </div>
      </div>

      <!-- 播放器主控件按钮组 -->
      <div class="flex items-center gap-4">
        <!-- 播放/暂停按钮 -->
        <button
          class="w-11 h-11 rounded-full border-none bg-primary text-white flex items-center justify-center p-0 transition-all shadow-md hover:scale-105 hover:shadow-lg active:scale-95"
          @click="togglePlay"
          title="播放/暂停"
        >
          <van-icon :name="isPlaying ? 'pause' : 'play'" :size="24" />
        </button>
      </div>

      <!-- 右侧控制按钮组 -->
      <div class="flex items-center gap-4">
        <!-- 更多功能菜单 -->
        <van-popover v-model:show="showMore" placement="top-end" :offset="[0, 8]">
          <template #reference>
            <img
              src="@/icons/svg/minute/audio_player_more.svg"
              class="cursor-pointer w-5 h-5"
              alt="more"
            />
          </template>
          <div class="flex flex-col gap-4 p-5">
            <div class="flex flex-col gap-2">
              <div class="speed-title">播放速度</div>
              <van-radio-group
                v-model="playbackRate"
                direction="vertical"
                @change="handleSpeedChange"
              >
                <van-radio
                  v-for="speed in speedOptions"
                  :key="speed"
                  :name="speed"
                  icon-size="16"
                  class="mb-2"
                  checked-color="#436BFF"
                >
                  {{ speed }}x
                </van-radio>
              </van-radio-group>
            </div>
          </div>
        </van-popover>
      </div>
    </div>

    <audio
      ref="audioRef"
      :src="audioSrc"
      @timeupdate="onTimeUpdate"
      @loadedmetadata="onLoadedMetadata"
      @ended="onEnded"
    ></audio>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted, defineEmits, defineExpose, onMounted } from "vue";
import { showToast } from "vant";
import "vant/es/toast/style";
import { useMinutesStore } from "@/store";
import {
  KeyboardDoubleArrowLeftRound,
  KeyboardDoubleArrowRightRound,
} from "@vicons/material";
import { useScreenSafeArea } from "@/composables/useScreenSafeArea";

import { Icon } from "@vicons/utils";

const props = defineProps<{
  audioSrc: string;
  needShadow: boolean;
}>();

const emit = defineEmits(["timeupdate", "onClickPlay"]);

const { bottom } = useScreenSafeArea();

useMinutesStore();

// 控制弹出层显示
const showMore = ref(false);

// 音频元素引用
const audioRef = ref<HTMLAudioElement>();

// 播放器状态
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const playbackRate = ref(1);

// 倍速选项
const speedOptions = [0.5, 1, 1.25, 1.5, 2];

// 计算进度百分比
const progress = computed(() => {
  if (!duration.value) return 0;
  return (currentTime.value / duration.value) * 100;
});

// 播放/暂停切换
const togglePlay = () => {
  if (!audioRef.value) return;
  if (isPlaying.value) {
    pause();
  } else {
    play();
  }
};

function play() {
  if (!audioRef.value) return;
  audioRef.value.play();
  emit("onClickPlay", true);
  isPlaying.value = true;
}

function pause() {
  if (!audioRef.value) return;
  audioRef.value.pause();
  emit("onClickPlay", false);
  isPlaying.value = false;
}

// 时间格式化
const formatTime = (time: number) => {
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${minutes}:${seconds.toString().padStart(2, "0")}`;
};

// 进度条点击跳转
const seek = (event: MouseEvent) => {
  if (!audioRef.value) return;

  const progressBar = event.currentTarget as HTMLElement;
  const rect = progressBar.getBoundingClientRect();
  const percent = (event.clientX - rect.left) / rect.width;
  audioRef.value.currentTime = percent * duration.value;
  if (!isPlaying.value) {
    play();
  }
};

// 倍速调节
const handleSpeedChange = (speed: number) => {
  if (!audioRef.value) return;
  playbackRate.value = speed;
  audioRef.value.playbackRate = speed;
};

// 音频事件处理
const isSliding = ref(false);
const onTimeUpdate = () => {
  if (!audioRef.value) return;
  currentTime.value = audioRef.value.currentTime;
  if (!isSliding.value) {
    emit("timeupdate", currentTime.value * 1000);
  }
};

const onLoadedMetadata = () => {
  if (!audioRef.value) return;
  duration.value = audioRef.value.duration;
};

const onEnded = () => {
  isPlaying.value = false;
  currentTime.value = 0;
};

// 组件销毁时停止播放
onUnmounted(() => {
  if (audioRef.value) {
    audioRef.value.pause();
  }
});

// 暴露方法给父组件
function seekTo(time: number) {
  if (audioRef.value && typeof time === "number") {
    if (!isPlaying.value) {
      togglePlay();
    }
    console.log("seekTo", time);
    audioRef.value.currentTime = time;
  }
}

const onSliderChange = (val: number) => {
  if (audioRef.value) {
    audioRef.value.currentTime = val;
    currentTime.value = val;
    if (!isPlaying.value) {
      togglePlay();
    }
  }
};

defineExpose({ seekTo, pause });
</script>

<style scoped lang="less"></style>
